import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { flatToTree } from '@/utils/util';
import { Button, CascaderSelect, Dialog, Form, Input, Select } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 14,
  },
  style: { marginBottom: 20 },
};

const RegionGroupForm = ({ groupName, modal, onSubmit, onCancel }) => {
  const { ccStationGroupStore: store } = useStore();
  const [group] = useState(observable({}));
  const [isViewMode] = useState(modal[0] === 'view');
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [treeData, setTreeData] = useState([]);

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (groupName) {
      _.assign(group, store.getGroup(groupName), { originName: groupName, regions: store.regions.map((r) => r.itemId) });
    } else if (store.selected) {
      group.city = store.selected.city;
    }
    if (store.selected?.city) setTreeData(_treeData(store.selected.city));
  }, [groupName]);

  function _treeData(city) {
    const regionInCity = store.regionsForCity(city);
    return flatToTree(regionInCity.map((r) => ({
      label: r.name,
      value: r.itemId,
      parentId: r.parentId,
      checkboxDisabled: r.extras.group?.value && (group.regions || []).indexOf(r.itemId) === -1,
    })), 'value');
  }

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(group, name, value);
    // 联动效果可以在这里通过设置station属性实现
    if (name === 'city') {
      setTreeData(_treeData(value));
      _.unset(group, 'regions');
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
    // console.log('form data: ', name, value, toJS(group));
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleSubmit = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: RegionGroupForm.jsx:77 _ errors:', errors);
      return;
    }
    onSubmit?.(group);
  };

  return (
    <Form
      isPreview={isViewMode}
      value={group}
      // colon
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FormItem
        label={t`城市：`}
        name="city"
        required
        {...formItemLayout}
      >
        <Select dataSource={store.cities.map((c) => ({ label: c.name, value: c.itemId }))} placeholder={t`请选择城市`} value={group.city} />
      </FormItem>
      <FormItem
        label={t`分组名称：`}
        name="name"
        required
        {...formItemLayout}
      >
        <Input placeholder={t`请输入分组名称`} value={group.name} />
      </FormItem>
      <FormItem
        label={t`区域：`}
        name="regions"
        {...formItemLayout}
      >

        <CascaderSelect
          dataSource={treeData}
          placeholder={t`请选择区域`}
          multiple
          style={{ width: '100%' }}
          // listStyle={{ width: '220px', height: '360px' }}
          checkStrictly
          checkedStrategy=""
          value={group.regions}
        />
      </FormItem>


      <DrawerFooter>
        <FormItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FormItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(RegionGroupForm);
